package com.hsy.swueasspider.ui

import android.app.Activity
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.animation.DecelerateInterpolator
import android.view.inputmethod.InputMethodManager
import android.webkit.WebView
import android.widget.EditText
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.marginBottom
import com.google.android.material.snackbar.Snackbar
import com.hsy.swueasspider.R
import com.hsy.swueasspider.TAG
import com.hsy.swueasspider.url.SwuEasUrl
import com.hsy.swueasspider.utils.SwuEasCookieUtils
import com.hsy.swueasspider.utils.SwuEasSpiderUtils

class SwuEasSpiderActivity : AppCompatActivity() {
    companion object {
        const val MODE = "mode"
        const val MODE_LOGIN = 1
        const val MODE_GET_COOKIE = 2

        const val USERNAME = "username"
        const val PASSWORD = "password"

        const val IS_LOGIN_SUCCEED = "isLoginSucceed"
        const val IS_GET_COOKIE_SUCCEED = "isGetCookieSucceed"
    }

    private lateinit var mWebView: WebView

    private var username = ""
    private var password = ""

    private var mode = 0

    private val resultIntent = Intent()

    private var loginCount = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_swu_eas_spider)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.root)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        mode = intent.getIntExtra(MODE, 0)
        username = intent.getStringExtra(USERNAME) ?: ""
        password = intent.getStringExtra(PASSWORD) ?: ""
        if (username.isEmpty() || password.isEmpty()) {
            Snackbar.make(findViewById(R.id.root), "账号或密码为空", Snackbar.LENGTH_SHORT).show()
            finish()
        }

        mWebView = findViewById<WebView?>(R.id.webView).apply {
//            setOnTouchListener { _, _ -> true }
        }
        SwuEasSpiderUtils.initWebView(mWebView)
        SwuEasSpiderUtils.initWebClient(mWebView)

        SwuEasSpiderUtils.addPageVisibleListener {
            mWebView.apply {
                evaluateJavascript("_goLogin();", null)
                evaluateJavascript(
                    "document.getElementById('loginName').value = '$username';",
                    null
                )
                evaluateJavascript(
                    "document.getElementById('password').value = '$password';",
                    null
                )
            }
        }
    }

    override fun onStart() {
        super.onStart()

        when (mode) {
            MODE_LOGIN -> {
                SwuEasSpiderUtils.addPageVisibleListener { url ->
                    when {
                        loginCount != 0 && url == SwuEasUrl.Base.LOGIN_CHECK -> {
                            resultIntent.putExtra(IS_LOGIN_SUCCEED, false)
                            setResult(Activity.RESULT_OK, resultIntent)
                            finish()
                        }

                        url.contains(SwuEasUrl.Base.AFTER_LOGIN) -> {
                            resultIntent.putExtra(IS_LOGIN_SUCCEED, true)
                            setResult(Activity.RESULT_OK, resultIntent)
                            finish()
                        }
                    }
                }
            }

            MODE_GET_COOKIE -> {
                if (SwuEasSpiderUtils.isCookieUsable()) {
                    resultIntent.putExtra(IS_GET_COOKIE_SUCCEED, true)
                    setResult(Activity.RESULT_OK, resultIntent)
                    finish()
                    return
                }

                SwuEasSpiderUtils.addPageVisibleListener { url ->
                    if (SwuEasSpiderUtils.isCookieUsable()) {
                        Snackbar.make(
                            findViewById(R.id.root),
                            "教务系统连接成功",
                            Snackbar.LENGTH_SHORT
                        ).show()
                        SwuEasSpiderUtils.refreshCurrentCookie()
                        SwuEasCookieUtils.writeCookie(this)
                        resultIntent.putExtra(IS_GET_COOKIE_SUCCEED, true)
                        setResult(Activity.RESULT_OK, resultIntent)
                        finish()
                    }

                    when {
                        loginCount != 0 && url == SwuEasUrl.Base.LOGIN_CHECK -> {
                            resultIntent.putExtra(IS_GET_COOKIE_SUCCEED, false)
                            setResult(Activity.RESULT_OK, resultIntent)
                            finish()
                        }

                        url.contains(SwuEasUrl.Base.AFTER_LOGIN) -> {
                            Snackbar.make(
                                findViewById(R.id.root),
                                "正在连接教务系统，请稍等...",
                                Snackbar.LENGTH_SHORT
                            ).show()

                            mWebView.loadUrl(SwuEasUrl.Base.ENTRY_TO_HALL)
                        }

                        url.contains(SwuEasUrl.Base.CHECK_IS_HALL) -> mWebView.loadUrl(SwuEasUrl.Base.ENTRY_TO_EAS)
                    }
                }
            }
        }

        mWebView.loadUrl(SwuEasUrl.Base.LOGIN)
    }

    override fun onDestroy() {
        super.onDestroy()

        SwuEasSpiderUtils.destroyWebView(mWebView)
        SwuEasSpiderUtils.logOutEas(mWebView)
    }
}